package com.suke.czx.modules.tb.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.suke.czx.modules.tb.entity.TbProduct;
import com.suke.czx.modules.tb.service.TbMessageService;
import com.suke.czx.modules.tb.service.TbProductService;
import com.suke.czx.modules.tb.vo.OrderCreateVO;
import com.suke.czx.modules.tb.vo.OrderVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.suke.czx.modules.tb.entity.TbOrderInfo;
import com.suke.czx.modules.tb.service.TbOrderInfoService;
import com.suke.czx.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;

import javax.annotation.Resource;


/**
 * 订单表
 *
 * @author developer
 * @email developer@163.com
 * @date 2025-05-19 07:16:43
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tb/orderInfo")
@Api(value = "TbOrderInfoController", tags = "订单表")
public class TbOrderInfoController extends AbstractController {
    private final TbOrderInfoService tbOrderInfoService;

    @Resource
    private TbProductService tbProductService;
    @Resource
    private TbMessageService tbMessageService;

    // 获取我的订单
    @ApiOperation(value = "获取我的订单")
    @PostMapping("/myOrder")
    public R myOrder(@RequestBody Map<String, Object> params) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        return R.ok().setData(tbOrderInfoService.myOrder(userId, params));
    }

    @ApiOperation(value = "订单详情")
    @PostMapping("/info")
    public R info(@RequestBody Map<String, Object> params) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        String orderId = params.get("orderId").toString();
        if (StringUtils.isBlank(orderId)) {
            return R.error("参数错误");
        }
        return R.ok().setData(tbOrderInfoService.getDetailById(orderId));
    }

    // 创建订单
    @ApiOperation(value = "创建订单")
    @PostMapping("/create")
    public R create(@RequestBody OrderCreateVO orderCreateVO) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        // 判断
        if (null == orderCreateVO.getProductId() || 0L == orderCreateVO.getProductId() ||
                StringUtils.isBlank(orderCreateVO.getShippingAddress())) {
            return R.error("参数错误");
        }

        TbProduct product = tbProductService.getById(orderCreateVO.getProductId());
        if(product == null){
            return R.error("商品不存在");
        }
        tbMessageService.setDeafultHeadMessage(orderCreateVO.getProductId(), userId, product.getUserId(), new Date());
        TbOrderInfo tbOrderInfo = new TbOrderInfo();
        tbOrderInfo.setProductId(orderCreateVO.getProductId());
        tbOrderInfo.setBuyerId(userId);
        tbOrderInfo.setSellerId(product.getUserId());
        if (!product.getShippingFee().equals(new BigDecimal(0))) {
            tbOrderInfo.setTotalAmount(product.getPrice().add(product.getShippingFee()));
        }else{
            tbOrderInfo.setTotalAmount(product.getPrice());
        }
        tbOrderInfo.setOrderSn(System.currentTimeMillis() + "");
        tbOrderInfo.setProductInfoJson(JSONUtil.toJsonStr(product));
        tbOrderInfo.setShippingAddress(orderCreateVO.getShippingAddress());
        // 待付款状态
        tbOrderInfo.setStatus("pending_payment");
        boolean saveOrderFlag = tbOrderInfoService.save(tbOrderInfo);
        if (saveOrderFlag) {
            // 发送购买消息
            tbMessageService.sendOrderMessage(tbOrderInfo, "orderStart");
            // 创建订单成功
            return R.ok().setData(tbOrderInfo);
        }
        return R.error("创建订单失败");
    }

    //取消订单
    @ApiOperation(value = "取消订单")
    @PostMapping("/cancel")
    public R cancel(@RequestBody Map<String, Object> params) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        String orderId = params.get("orderId").toString();
        if (StringUtils.isBlank(orderId)) {
            return R.error("参数错误");
        }
        String cancelReason = (String) params.get("cancelReason");
        if (StringUtils.isBlank(cancelReason)) {
            return R.error("参数错误");
        }
        TbOrderInfo tbOrderInfo = tbOrderInfoService.getById(orderId);
        if (tbOrderInfo == null) {
            return R.error("订单不存在");
        }
        if (tbOrderInfo.getStatus().equals("pending_payment")) {
            tbOrderInfo.setStatus("cancelled");
            tbOrderInfo.setCancelReason(cancelReason);
            // 发送取消消息
            tbMessageService.sendOrderMessage(tbOrderInfo, "orderCancel");
            boolean updateFlag = tbOrderInfoService.updateById(tbOrderInfo);
            if (updateFlag) {
                return R.ok("取消订单成功");
            }
        }
        return R.error("取消订单失败");
    }

    // 确定支付
    @ApiOperation(value = "确定支付")
    @PostMapping("/confirmPay")
    public R confirmPay(@RequestBody Map<String, Object> params) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        String orderId = params.get("orderId").toString();
        if (StringUtils.isBlank(orderId)) {
            return R.error("参数错误");
        }

        TbOrderInfo tbOrderInfo = tbOrderInfoService.getById(orderId);
        if (tbOrderInfo == null) {
            return R.error("订单不存在");
        }
        if (tbOrderInfo.getStatus().equals("pending_payment")) {
            tbOrderInfo.setStatus("paid");
            // 发送取消消息
            tbMessageService.sendOrderMessage(tbOrderInfo, "orderPay");
            boolean updateFlag = tbOrderInfoService.updateById(tbOrderInfo);
            if (updateFlag) {
                return R.ok("支付成功");
            }
        }
        return R.error("支付失败");
    }

    // 确定发货
    @ApiOperation(value = "确定发货")
    @PostMapping("/confirmShipped")
    public R confirmShipped(@RequestBody Map<String, Object> params) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        String orderId = params.get("orderId").toString();
        if (StringUtils.isBlank(orderId)) {
            return R.error("参数错误");
        }

        TbOrderInfo tbOrderInfo = tbOrderInfoService.getById(orderId);
        if (tbOrderInfo == null) {
            return R.error("订单不存在");
        }
        if (tbOrderInfo.getStatus().equals("paid")) {
            tbOrderInfo.setStatus("shipped");
            // 发送发货消息
            tbMessageService.sendOrderMessage(tbOrderInfo, "orderShipped");
            boolean updateFlag = tbOrderInfoService.updateById(tbOrderInfo);
            if (updateFlag) {
                return R.ok("操作成功");
            }
        }
        return R.error("操作失败");
    }

    // 确认收货
    @ApiOperation(value = "确认收货")
    @PostMapping("/confirmCompleted")
    public R confirmCompleted(@RequestBody Map<String, Object> params) {
        String userId = getUserId();
        if (StrUtil.isEmpty(userId)) {
            return R.error("请先登录");
        }
        String orderId = params.get("orderId").toString();
        if (StringUtils.isBlank(orderId)) {
            return R.error("参数错误");
        }

        TbOrderInfo tbOrderInfo = tbOrderInfoService.getById(orderId);
        if (tbOrderInfo == null) {
            return R.error("订单不存在");
        }
        if (tbOrderInfo.getStatus().equals("shipped")) {
            tbOrderInfo.setStatus("completed");
            // 确认收货消息
            tbMessageService.sendOrderMessage(tbOrderInfo, "orderCompleted");
            boolean updateFlag = tbOrderInfoService.updateById(tbOrderInfo);
            if (updateFlag) {
                return R.ok("操作成功");
            }
        }
        return R.error("操作失败");
    }



    /**
     * 列表
     */
    @ApiOperation(value = "订单表列表")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        QueryWrapper<TbOrderInfo> queryWrapper = new QueryWrapper<>();
        final String keyword = mpPageConvert.getKeyword(params);
        if (StrUtil.isNotEmpty(keyword)) {

        }
        IPage<TbOrderInfo> listPage = tbOrderInfoService.page(mpPageConvert.<TbOrderInfo>pageParamConvert(params), queryWrapper);
        return R.ok().setData(listPage);
    }


    /**
     * 新增订单表
     */
    @ApiOperation(value = "新增订单表数据")
    @SysLog("新增订单表数据")
        @PostMapping()
        public R save(@RequestBody TbOrderInfo tbOrderInfo) {
        tbOrderInfoService.save(tbOrderInfo);
        return R.ok();
    }


    /**
     * 修改
     */
    @ApiOperation(value = "修改订单表数据")
    @SysLog("修改订单表数据")
        @PutMapping()
        public R update(@RequestBody TbOrderInfo tbOrderInfo) {
        tbOrderInfoService.updateById(tbOrderInfo);
        return R.ok();
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除订单表数据")
    @SysLog("删除订单表数据")
        @DeleteMapping()
        public R delete(@RequestBody TbOrderInfo tbOrderInfo) {
        tbOrderInfoService.removeById(tbOrderInfo.getId());
        return R.ok();
    }

}
